﻿using AutoMapper;
using MediatR;
using RBAC.Domain.Dto.Output;
using RBAC.Domain.RBAC;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Read.Api.Application.Command.User;

namespace RBAC.Read.Api.Application.Handler.User
{
    public class GetUserHandler : IRequestHandler<GetUserCommand, APIResult<List<GetUserListDto>>>
    {
        private readonly IBaseRepository<UserModel> userRepository;
        private readonly ILogger<GetUserHandler> logger;
        private readonly IBaseRepository<RoleModel> roleRepository;
        private readonly IBaseRepository<UserRoleModel> userRoleRepository;
        private readonly IBaseRepository<RolePermissionModel> rolePermissionRepository;
        private readonly IBaseRepository<PermissionModel> permissionRepository;
        private readonly IMapper mapper;

        public GetUserHandler(IBaseRepository<UserModel> userRepository, ILogger<GetUserHandler> logger, IBaseRepository<RoleModel> roleRepository, IBaseRepository<UserRoleModel> userRoleRepository, IBaseRepository<RolePermissionModel> rolePermissionRepository, IBaseRepository<PermissionModel> permissionRepository, IMapper mapper)
        {
            this.userRepository = userRepository;
            this.logger = logger;
            this.roleRepository = roleRepository;
            this.userRoleRepository = userRoleRepository;
            this.rolePermissionRepository = rolePermissionRepository;
            this.permissionRepository = permissionRepository;
            this.mapper = mapper;
        }
        /// <summary>
        /// 获取用户列表，包括角色和权限信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public  Task<APIResult<List<GetUserListDto>>> Handle(GetUserCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<GetUserListDto>> res = new APIResult<List<GetUserListDto>>();

            try
            {
                // 一次性加载所有需要的数据到内存中，避免多次数据库连接冲突
                var users = userRepository.GetALL().Where(x => x.IsDeleted == false).ToList();
                var userRoles = userRoleRepository.GetALL().Where(x => x.IsDeleted == false).ToList();
                var roles = roleRepository.GetALL().Where(x => x.IsDeleted == false).ToList();
                var rolePermissions = rolePermissionRepository.GetALL().Where(x => x.IsDeleted == false).ToList();
                var permissions = permissionRepository.GetALL().Where(x => x.IsDeleted == false).ToList();

                // 使用LINQ Join优化性能，构建用户列表，包含角色和权限信息
                var userListDto = users.Select(user =>
                {
                    // 获取用户的角色
                    var userRoleIds = userRoles.Where(ur => ur.UserId == user.Id).Select(ur => ur.RoleId).ToList();
                    var userRoleList = roles.Where(r => userRoleIds.Contains(r.Id)).ToList();

                    // 获取用户所有角色的权限（去重）
                    var userPermissionIds = rolePermissions
                        .Where(rp => userRoleIds.Contains(rp.RoleId))
                        .Select(rp => rp.PermissionId)
                        .Distinct()
                        .ToList();

                    var userPermissions = permissions.Where(p => userPermissionIds.Contains(p.Id)).ToList();

                    return new GetUserListDto
                    {
                        Id = user.Id,
                        WorkNumber = user.WorkNumber,
                        UserName = user.UserName,
                        Password = user.Password,
                        FullName = user.FullName,
                        Sex = user.Sex,
                        Address = user.Address,
                        Mobile = user.Mobile,
                        RenPing = user.RenPing,
                        DepartmentId = user.DepartmentId,
                        RegistrationFee = user.RegistrationFee,
                        RoleId = userRoleList.Select(r => r.Id).ToList(),
                        RoleName = userRoleList.Select(r => r.RoleName).ToList(),
                        PermissionIds = userPermissions.Select(p => p.Id).ToList(),
                        PermissionNames = userPermissions.Select(p => p.PermissionName).ToList(),
                        IsEnable = user.IsEnable
                    };
                }).ToList();

                res.Code = APIEnums.Success;
                res.Data = userListDto;
                res.Msg = "获取用户列表成功";
                logger.LogInformation("获取用户列表成功，共获取到 {Count} 个用户", userListDto.Count);

                return Task.FromResult(res);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取用户列表失败");
                res.Code = APIEnums.Error;
                res.Msg = "获取用户列表失败";
                res.Data = new List<GetUserListDto>();
                return Task.FromResult(res);
            }
        }
    }
}
